package com.lichuandi.crawler;

import com.google.gson.JsonParser;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/crawler")
public class SichuanAirVcode {
    @GetMapping("/sichuanair3")
    public  String getPageContent() {
        try {
            // 主页
           final String url = "https://me.sichuanair.com/login.shtml";
            // 登录页面
            final String url2 = "https://me.sichuanair.com/api/v1/security/loginSC";
           final String urlFlight = "https://me.sichuanair.com/api/v1/plugins/LM_FLIGHT_SEARCH_LIST";
            Connection connection = Jsoup.connect(url).
                    header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0");
            connection.method(Connection.Method.GET);
            connection.followRedirects(false);
            // 获取响应
            Connection.Response response = connection.execute();
            Map<String, String> cookies = response.cookies();
            System.out.println(cookies);
            Document document = Jsoup.parse(response.body());
            Elements select = document.select("#img_vcode");

            String logs = "https://me.sichuanair.com/verifyScCode?t_" + new Date().getTime();
            System.out.println(logs);

            Connection.Response execute = Jsoup.connect(logs)
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36")
                    .ignoreContentType(true)
                    .followRedirects(false)
                    .method(Connection.Method.GET)
                    .cookies(response.cookies())
                    .execute();
            System.out.println(execute.cookies());
            Map<String, String> cookies2 = execute.cookies();
            byte[] bytes = execute.bodyAsBytes();
            String s = ChaoJiYing.PostPic("amfreak", "qwe12345", "914695", "3004", "0", bytes);
            System.out.println(s);
            String pic_str = JsonParser.parseString(s).getAsJsonObject().get("pic_str").getAsString();
            System.out.println(pic_str);


            Elements elements = document.select("#mform");

            // 获取cookie和表单
            Map<String, String> datas = new HashMap<>();


            for (Element e: elements.get(0).getAllElements()) {
                // 设置用户
                if (e.attr("name").equals("username")){
                    e.attr("value", "018750");
                }
                if (e.attr("name").equals("userPassword")){
                    e.attr("value", "NUvjWmbmzFZIS1hOd0Uo0rXjJcF/W+94PTT1DBLyAV2dIALLMMktJjjY6y4AQD+QXbkxNgASvSjEMC2ldO+14g==");
                }
                if (e.attr("name").equals("vCode")){
                    e.attr("value",pic_str);

                }
                // 排除空值表单属性
                if (e.attr("name").length() > 0){
                    datas.put(e.attr("name"), e.attr("value"));
                }
            }

            // IP和ip_parse_data信息
         //   datas.put("ip","171.221.84.122");
           // datas.put("ip_parse_data","{\"ip\":\"171.221.84.122\",\"mainInfo\":\"中国四川省成都市双流区\",\"subInfo\":\"电信\"}");

            //  Element body = document.body();

           // String pageContent = document.html();

            // 第二次请求 POST的方式提交表单数据以及cookie
            Connection connect = Jsoup.connect("https://me.sichuanair.com/api/v1/security/loginSC");
            connect.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0");
            // 设置cookie和post上面的map数据
            Connection.Response login = connect.ignoreContentType(true).followRedirects(false)
                    .method(Connection.Method.POST).data(datas).cookies(execute.cookies()).execute();
            System.out.println(login.body());
            // 登录成功之后的cookie信息，保存在本地，以后登录时候，只需一次登录即可
            Map<String, String> map = login.cookies();
            for (String s2: map.keySet()) {
                System.out.println(s2+ ":" + map.get(s2));
            }
            Document document2 = Jsoup.parse(login.body());
            String html = document2.html();
            //登录之后的操作
            // 请求爬取的内容
            /**
             * base4code: ZUUU
             * flightDate: 2023-12-06
             * flightDate1: 2023-12-07
             * jcType:
             * actype1: ()
             * dep_4code:
             * arr_4code:
             * acno:
             * actype:
             * flightNo:
             * notView:
             * onlyAf:
             * page: 1
             * rows: 19
             * */
            // 参数
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("base4code","ZUUU");
            hashMap.put("flightDate","2023-12-06");
            hashMap.put("flightDate1","2023-12-07");
            hashMap.put("jcType","");
            hashMap.put("actype1","");
            hashMap.put("dep_4code","");
            hashMap.put("acno","");
            hashMap.put("actype","");
            hashMap.put("flightNo","");
            hashMap.put("notView","");
            hashMap.put("onlyAf","");
            hashMap.put("page","1");
            hashMap.put("rows","19");

            Connection connectFlight = Jsoup.connect(urlFlight);
            // 设置header
            connectFlight.header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36");
            /*connectFlight.header();
            connectFlight.header();
            connectFlight.header();
            connectFlight.header();*/
            // 保存cookie
            connectFlight.cookies(datas);
            Connection.Response list = connectFlight.ignoreContentType(true)
                    .followRedirects(false)
                    .method(Connection.Method.POST)
                    .data(hashMap)
                    .cookies(login.cookies())
                    .execute();
            String body = list.body();
            return body;

        } catch (Exception e) {
            return "Error: " + e.getMessage();
        }
    }

    private void getStream(URL url1) throws IOException {
        InputStream inputStream = url1.openStream();
        FileOutputStream outputStream = new FileOutputStream("F:\\vcode\\myVCode.jpg");
        byte[] bytes = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes,0, bytesRead);
        }
        outputStream.close();
        inputStream.close();
        // return outputStream;
    }
}
